package sync_config

import (
	syncConfigDto "news_for_deepseek_interface/dto/admin/sync_config"
	"news_for_deepseek_interface/logger"
	"news_for_deepseek_interface/model"
	"news_for_deepseek_interface/model/sync"

	"time"
)

func Update(params syncConfigDto.UpdateRequest) error {

	db := model.GetInstance().GetDB()

	//立即执行
	if params.Execute != nil {

		//条件初始化
		var syncMessage SyncMessage
		syncMessage = SyncMessage{
			TypeClassifyId:     params.TypeClassifyId,
			BusinessClassifyId: params.BusinessClassifyId,
			StartId:            params.StartId,
			Number:             params.Number,
			Type:               2,
		}
		//同步文章
		if err := syncMessage.SyncNews(); err != nil {
			return err
		}
	}

	//执行时间格式化
	hourFormat := 0
	if params.Hour != nil {
		// 解析时间
		t, err := time.Parse("15:04", *params.Hour)
		if err != nil {
			logger.Error("解析时间失败：" + err.Error())
			return err
		}

		// 提取小时部分并转为 int
		hourFormat = t.Hour()
	}
	if err := db.Model(&sync.SyncConfigModel{}).
		Where("id = ?", params.Id).
		Updates(map[string]interface{}{
			"type_classify_id":     params.TypeClassifyId,
			"business_classify_id": params.BusinessClassifyId,
			"number":               params.Number,
			"hour":                 params.Hour,
			"hour_format":          hourFormat,
			"updated_at":           time.Now(),
		}).Error; err != nil {
		return err
	}

	if params.Execute == nil {
		if err := db.Model(&sync.SyncConfigModel{}).
			Where("id = ?", params.Id).
			Updates(map[string]interface{}{
				"start_id": params.StartId,
			}).Error; err != nil {
			return err
		}

	}

	return nil
}
